package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 查询商家类型列表
     *
     * @return
     */
    @Override
    public Result queryTypeList() {
        String cacheShopTypeKey = CACHE_SHOP_TYPE_KEY;
        // 1. 查询redis中的商户类型数据
        List<String> jsonList= stringRedisTemplate.opsForList().range(cacheShopTypeKey, 0, -1);
        if (!CollUtil.isEmpty(jsonList)) {
            // 2. 命中，将字符串转换成shoptype对象，返回商户列表
            ArrayList<ShopType> shopTypeList = new ArrayList<>(jsonList.size());
            for (String shopTypeStr : jsonList) {
                shopTypeList.add(JSONUtil.toBean(shopTypeStr, ShopType.class));
            }
            return Result.ok(shopTypeList);
        }

        // 3. 未命中，查询数据库中的商户列表
        List<ShopType> list = query().orderByAsc("sort").list();
        // 4. 未命中，数据不存在
        if (CollUtil.isEmpty(list)) {
            return Result.fail("商户类型列表为空！");
        }

        jsonList = new ArrayList<>();
        // 遍历集合，将Shop对象转换成 字符串
        for (ShopType shopType : list) {
           jsonList.add(JSONUtil.toJsonStr(shopType));
        }

        // 5. 将商户列表数据写入redis
        stringRedisTemplate.opsForList().rightPushAll(cacheShopTypeKey,jsonList);
        stringRedisTemplate.expire(cacheShopTypeKey,CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        // 6. 返回商户列表
        return Result.ok(list);
    }
}
